<?php

namespace app\api\model;

class CouponUsed extends \app\common\model\CouponUsed
{
    /**
     * 获取已使用的优惠券 coupon_id => order_sn
     * @param $oauthId
     * @return array
     */
    public static function getColumn($oauthId)
    {
        return static::where(['oauth_id' => $oauthId])->column('order_sn', 'coupon_id');
    }

    /**
     * 获取已使用的优惠券列表
     * @param $oauthId
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($oauthId, $page, $size)
    {
        $offset = ($page - 1) * $size;

        $sql = static::field('c.id, c.name, c.money, c.start_time AS startTime, c.end_time AS endTime, c.rule')
            ->alias('u')
            ->join('coupon c', 'u.coupon_id = c.id')
            ->where([
                'u.oauth_id' => $oauthId,
            ]);

        $model = $sql->order(['u.create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        foreach ($model as $key => $value) {
            $model[$key]['startTime'] = get_date($value['startTime']);
            $model[$key]['endTime'] = get_date($value['endTime']);
        }

        return [
            'list' => $model,
            'count' => $sql->count()
        ];
    }
}